﻿#if WINDOWS_PHONE
using System;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using XamlMvp.Modelling;

namespace XamlMvp.Controls
{
    public partial class MvpPage : PhoneApplicationPage
    {        
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            if (NavigatedFrom != null)
            {
                MvpNavigationEventArgs args;
                if (e.IsAppExternal())
                {
                    FocusHack();
                    args = new MvpNavigationEventArgs(e.Content as MvpPage, PhoneApplicationService.Current.State, true);
                }
                else
                {
                    args = new MvpNavigationEventArgs(e.Content as MvpPage, new Dictionary<string, object>(), false);
                }
                NavigatedFrom(this, args);
                Binders.Presenters.Context = args;
            }
        }           

        partial void FocusHack()
        {
            TextBox textbox = FocusManager.GetFocusedElement() as TextBox;
            if (textbox != null)
            {
                var binding = textbox.GetBindingExpression(TextBox.TextProperty);
                binding.UpdateSource();
            }
        }
    }

}
#endif